package com.xxh.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

@Slf4j
@Configuration
public class Oauth2ExceptionTranslatorConfiguration {
    @Bean
    public WebResponseExceptionTranslator<OAuth2Exception> oauth2ResponseExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            @Override
            public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                OAuth2Exception body = OAuth2Exception.create(OAuth2Exception.ACCESS_DENIED, e.getMessage());
                // 捕获后在返回值添加code、message
                body.addAdditionalInformation("code", String.valueOf(400));
                body.addAdditionalInformation("message", "用户名或密码错误");
                HttpHeaders headers = new HttpHeaders();
                return new ResponseEntity<>(body, headers, HttpStatus.UNAUTHORIZED);
//                return new ResponseEntity<>(body, headers, HttpStatus.OK);
            }
        };
    }

}
